<template>
	<view class="content">
		<view v-if="isShowLogin">
			 <button @click="login">授权登录</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				isShowLogin:false,
			}
		},
		onLoad() {
			if(uni.getStorageSync('token')){
				uni.reLaunch({
					// url: '/pages/home/home',
					url:'/pages/classification/classification',
					// url:'/pages/user/user'
					// url: '/pages/order/order',
				})
			}else{
				this.getSessionId()
			}
		},
		methods: {
			//登录
			login(){
				// console.log("login")
				uni.getUserProfile({
					desc:"授权登录",
					success:(res)=>{
						// console.log(res)
						let wxAuth = {
							encryptedData: res.encryptedData,
							iv: res.iv,
							sessionId: uni.getStorageSync("sessionId")
						}
						this.$http("/wx-user/authLogin", "post", wxAuth).then((res) => {
							// console.log(res)
							if (res.data.data.token) {
								uni.setStorage({
									key: 'token',
									data: res.data.data.token,
									success: function() {
										uni.reLaunch({
											url: '/pages/classification/classification'
										})
										uni.showToast({
											title: res.data.message,
											icon: "success"
										})
									}
								})
							} else {
								uni.showToast({
									title: res.data.message,
									icon: "none"
								})
							}
						})
					},
					fail:(res)=>{
						uni.showToast({
							title: "您已经拒绝授权登录！",
							icon: "error",
							duration: 2000
						})
					}
				})
				
			},
			//获取sessionId
			getSessionId() {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						console.log(res)
						this.$http("/wx-user/getSessionId", "get", {
							code: res.code
						}).then(res2 => {
							console.log(res2)
							if (res2.data.data.sessionId) {
								uni.setStorageSync("sessionId", res2.data.data.sessionId)
								this.isShowLogin = true
							}
							
						})
					}
				})
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
